<template>
  <div class="echarts-container">
    <h1 class="page-title" style="font-size: 50px; font-weight:bold;">出入量</h1>
    
    <div class="header">
      <div class="patient-info">
        <span class="patient-label" style="font-size: 25px;">当前病人：</span>
        <span class="patient-name" style="font-size: 25px;">{{ patientName }}</span>

      </div>
      <div class="date-section">
        <span class="date-label" style="font-size: 20px;">统计时间：</span>
        <input type="date" class="date-input" />
        <span class="separator">-</span>
        <input type="date" class="date-input" />
        <button class="query-btn">查询</button>
        <button class="query-btn" @click="returndetailed()">返回</button>
      </div>
    </div>

    <div class="charts-section">
      <div class="chart-block">
        <h2 class="chart-title" style="font-size: 35px; font-weight: bold;">入量统计</h2>
        <div class="chart-area">
          <div class="chart-container">
            <div ref="inChart" class="chart"></div>
          </div>
          <div class="volume-info">
            <div class="volume-text" style="font-size: 25px;">总入量 (ml)</div>
            <div class="volume-value" style="font-size: 40px;">{{ totalIn }}</div>
          </div>
        </div>
        <div class="data-list">
          <div v-for="(value, name, index) in categorizedInData" :key="name" class="data-row">
            <div class="data-label">
              <span class="dot" :class="getInDotClass(name, index)"></span>
              <span>{{ name }}</span>
            </div>
            <div class="progress-bar">
              <div class="progress" 
                   :class="getInProgressClass(name, index)"
                   :style="{width: (value / totalIn * 100) + '%'}"></div>
            </div>
            <div class="data-value">{{ value }}ml</div>
          </div>
        </div>
      </div>

      <div class="chart-block">
        <h2 class="chart-title" style="font-size: 35px; font-weight: bold;">出量统计</h2>
        <div class="chart-area">
          <div class="chart-container">
            <div ref="outChart" class="chart"></div>
          </div>
          <div class="volume-info">
            <div class="volume-text" style="font-size: 25px;">总出量 (ml)</div>
            <div class="volume-value" style="font-size: 40px;">{{ totalOut }}</div>
          </div>
        </div>
        <div class="data-list">
          <div v-for="(value, name, index) in categorizedOutData" :key="name" class="data-row">
            <div class="data-label">
              <span class="dot" :class="getOutDotClass(name, index)"></span>
              <span>{{ name }}</span>
            </div>
            <div class="progress-bar">
              <div class="progress" 
                   :class="getOutProgressClass(name, index)"
                   :style="{width: (value / totalOut * 100) + '%'}"></div>
            </div>
            <div class="data-value">{{ value }}ml</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const inChart = ref(null)
const outChart = ref(null)

// 获取传递过来的患者编号和名称
const patientCode = route.query.patientCode || 'PAT001'
const patientName = route.query.patientName || '未知患者'
console.log('获取到的患者信息:', patientCode, patientName)

// 入量和出量数据
const inData = ref([])
const outData = ref([])

// 按类型分类的入量和出量数据
const categorizedInData = ref({})
const categorizedOutData = ref({})

// 获取患者出入量数据
const getPatientFluidData = () => {
  console.log('获取出入量数据, 患者编号:', patientCode)
  
  // 调用入量API
  fetchInData()
  
  // 调用出量API
  fetchOutData()
}

// 获取入量数据
const fetchInData = () => {
  console.log('请求入量数据...')
  proxy.http.get(`/api/DoctorManageController/GetinRecord?patientCode=${patientCode}`)
    .then(res => {
      console.log('入量数据请求成功:', res)
      if (res && Array.isArray(res)) {
        // 存储原始数据
        inData.value = res
        
        // 对入量数据按类型分类
        categorizedInData.value = {}
        res.forEach(item => {
          if (!categorizedInData.value[item.adiName]) {
            categorizedInData.value[item.adiName] = 0
          }
          categorizedInData.value[item.adiName] += item.inValue
        })
        
        // 更新入量图表
        setTimeout(() => {
          initInChart()
        }, 300)
      } else {
        console.error('入量数据格式错误:', res)
      }
    })
    .catch(err => {
      console.error('获取入量数据失败:', err)

      // 对入量数据按类型分类
      categorizedInData.value = {}
      testData.forEach(item => {
        if (!categorizedInData.value[item.adiName]) {
          categorizedInData.value[item.adiName] = 0
        }
        categorizedInData.value[item.adiName] += item.inValue
      })
      
      // 更新入量图表
     setInterval(() => {
        initInChart()
      }, 3000)
    })
}

// 获取出量数据
const fetchOutData = () => {
  console.log('请求出量数据...')
  proxy.http.get(`/api/DoctorManageController/GetOutRecord?patientCode=${patientCode}`)
    .then(res => {
      console.log('出量数据请求成功:', res)
      if (res && Array.isArray(res)) {
        // 存储原始数据
        outData.value = res
        
        // 对出量数据按类型分类
        categorizedOutData.value = {}
        res.forEach(item => {
          if (!categorizedOutData.value[item.outputName]) {
            categorizedOutData.value[item.outputName] = 0
          }
          categorizedOutData.value[item.outputName] += item.outValue
        })
        
        // 更新出量图表
        setInterval(() => {
          initOutChart()
        }, 3000)
      } else {
        console.error('出量数据格式错误:', res)
      }
    })
    .catch(err => {
      console.error('获取出量数据失败:', err)
      
      
      // 对出量数据按类型分类
      categorizedOutData.value = {}
      testData.forEach(item => {
        if (!categorizedOutData.value[item.outputName]) {
          categorizedOutData.value[item.outputName] = 0
        }
        categorizedOutData.value[item.outputName] += item.outValue
      })
      
      // 更新出量图表
      setInterval(() => {
        initOutChart()
      }, 3000)
    })
}

// 计算总入量
const totalIn = computed(() => {
  let total = 0
  for (const key in categorizedInData.value) {
    total += categorizedInData.value[key]
  }
  return total
})

// 计算总出量
const totalOut = computed(() => {
  let total = 0
  for (const key in categorizedOutData.value) {
    total += categorizedOutData.value[key]
  }
  return total
})

// 初始化入量图表
const initInChart = () => {
  console.log('初始化入量图表')
  if (!inChart.value) {
    console.error('入量图表容器不存在')
    return
  }
  
  try {
    const chart = echarts.init(inChart.value)
    
    // 将分类数据转换为图表数据格式
    const chartData = []
    
    // 更鲜明的颜色数组
    const colorArray = [
      '#FF6B6B', // 鲜红色
      '#4ECDC4', // 绿松石色
      '#45B7D1', // 海蓝色
      '#FFA624', // 橙色
      '#A66CFF', // 亮紫色
      '#1A936F', // 森林绿
      '#C9A227', // 金黄色
      '#FF8066', // 珊瑚色
      '#3A86FF', // 蓝色
      '#8BC34A', // 草绿色
      '#F94892', // 粉红色
      '#6A4C93'  // 紫罗兰色
    ]
    
    // 为每个数据项分配唯一颜色
    let index = 0
    for (const key in categorizedInData.value) {
      chartData.push({
        value: categorizedInData.value[key],
        name: key,
        itemStyle: { color: colorArray[index % colorArray.length] }
      })
      index++
    }
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}ml ({d}%)'
      },
      series: [{
        name: '入量',
        type: 'pie',
        radius: ['0%', '75%'],
        center: ['40%', '50%'],
        label: {
          show: true,
          position: 'inside',
          formatter: '{d}%',
          color: '#fff',
          fontSize: 14,
          fontWeight: 'bold'
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: '#fff'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: chartData
      }]
    }
    chart.setOption(option)
    console.log('入量图表初始化成功')
  } catch (err) {
    console.error('初始化入量图表失败:', err)
  }
}

// 初始化出量图表
const initOutChart = () => {
  console.log('初始化出量图表')
  if (!outChart.value) {
    console.error('出量图表容器不存在')
    return
  }
  
  try {
    const chart = echarts.init(outChart.value)
    
    // 将分类数据转换为图表数据格式
    const chartData = []
    
    // 更鲜明的颜色数组（与入量图表不同）
    const colorArray = [
      '#FF5733', // 亮红橙色
      '#5DADE2', // 湖蓝色
      '#F4D03F', // 黄色
      '#58D68D', // 薄荷绿
      '#AF7AC5', // 淡紫色
      '#EC7063', // 珊瑚粉
      '#3498DB', // 蓝色
      '#F39C12', // 琥珀色
      '#2ECC71', // 翠绿色
      '#E74C3C', // 砖红色
      '#9B59B6', // 紫水晶色
      '#1ABC9C'  // 绿松石色
    ]
    
    // 为每个数据项分配唯一颜色
    let index = 0
    for (const key in categorizedOutData.value) {
      chartData.push({
        value: categorizedOutData.value[key],
        name: key,
        itemStyle: { color: colorArray[index % colorArray.length] }
      })
      index++
    }
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}ml ({d}%)'
      },
      series: [{
        name: '出量',
        type: 'pie',
        radius: ['0%', '75%'],
        center: ['40%', '50%'],
        label: {
          show: true,
          position: 'inside',
          formatter: '{d}%',
          color: '#fff',
          fontSize: 14,
          fontWeight: 'bold'
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: '#fff'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: chartData
      }]
    }
    chart.setOption(option)
    console.log('出量图表初始化成功')
  } catch (err) {
    console.error('初始化出量图表失败:', err)
  }
}

onMounted(() => {
  console.log('页面已挂载，开始获取数据')
  // 获取患者出入量数据
  getPatientFluidData()
  
  // 窗口调整时更新图表大小
  window.addEventListener('resize', () => {
    if (!inChart.value || !outChart.value) return
    
    try {
      const inChartInstance = echarts.getInstanceByDom(inChart.value)
      const outChartInstance = echarts.getInstanceByDom(outChart.value)
      inChartInstance?.resize()
      outChartInstance?.resize()
    } catch (err) {
      console.error('调整图表大小失败:', err)
    }
  })
})

//返回按钮
const returndetailed = () => {
  router.push("/ShowDoctor")
}

// 获取入量图表的点类
const getInDotClass = (name, index) => {
  // 与饼图使用相同的颜色数组
  const colorArray = [
    '#FF6B6B', // 鲜红色
    '#4ECDC4', // 绿松石色
    '#45B7D1', // 海蓝色
    '#FFA624', // 橙色
    '#A66CFF', // 亮紫色
    '#1A936F', // 森林绿
    '#C9A227', // 金黄色
    '#FF8066', // 珊瑚色
    '#3A86FF', // 蓝色
    '#8BC34A', // 草绿色
    '#F94892', // 粉红色
    '#6A4C93'  // 紫罗兰色
  ]
  
  // 获取对应的CSS类
  return 'custom-color-' + index % colorArray.length
}

// 获取入量图表的进度条类
const getInProgressClass = (name, index) => {
  // 使用相同的颜色映射
  return getInDotClass(name, index)
}

// 获取出量图表的点类
const getOutDotClass = (name, index) => {
  // 与饼图使用相同的颜色数组
  const colorArray = [
    '#FF5733', // 亮红橙色
    '#5DADE2', // 湖蓝色
    '#F4D03F', // 黄色
    '#58D68D', // 薄荷绿
    '#AF7AC5', // 淡紫色
    '#EC7063', // 珊瑚粉
    '#3498DB', // 蓝色
    '#F39C12', // 琥珀色
    '#2ECC71', // 翠绿色
    '#E74C3C', // 砖红色
    '#9B59B6', // 紫水晶色
    '#1ABC9C'  // 绿松石色
  ]
  
  // 获取对应的CSS类
  return 'custom-color-out-' + index % colorArray.length
}

// 获取出量图表的进度条类
const getOutProgressClass = (name, index) => {
  // 使用相同的颜色映射
  return getOutDotClass(name, index)
}
</script>

<style scoped>
.echarts-container {
  padding: 20px;
  background: #fff;
}

.page-title {
  text-align: center;
  font-size: 20px;
  color: #333;
  margin-bottom: 30px;
  font-weight: normal;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.patient-label {
  color: #f56c6c;
  font-size: 14px;
}

.patient-name {
  font-size: 14px;
}

.date-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-label {
  font-size: 14px;
  color: #333;
}

.date-input {
  width: 150px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
  color: #606266;
}

.separator {
  color: #606266;
}

.query-btn {
  background: #409EFF;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.charts-section {
  display: flex;
  gap: 20px;
}

.chart-block {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-title {
  color: #409EFF;
  font-size: 16px;
  margin-bottom: 20px;
  font-weight: normal;
}

.chart-area {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  min-height: 300px;
}

.chart-container {
  width: 70%;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.volume-info {
  width: 30%;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.volume-text {
  font-size: 14px;
  color: #606266;
}

.volume-value {
  font-size: 24px;
  color: #303133;
  font-weight: bold;
}

.data-list {
  margin-top: 20px;
}

.data-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.data-label {
  width: 60px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #606266;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.dot.blue { background-color: #409EFF; }
.dot.orange { background-color: #F6BD16; }
.dot.purple { background-color: #E8684A; }
.dot.green { background-color: #6DC8EC; }

.dot.red { background-color: #EE6666; }
.dot.teal { background-color: #73C0DE; }
.dot.forest { background-color: #3BA272; }
.dot.salmon { background-color: #FC8452; }
.dot.purple-dark { background-color: #9A60B4; }
.dot.navy { background-color: #5470C6; }
.dot.lime { background-color: #91CC75; }
.dot.yellow { background-color: #FAC858; }
.dot.pink { background-color: #EA7CCC; }

.progress-bar {
  flex: 1;
  height: 6px;
  background: #f5f7fa;
  border-radius: 3px;
  overflow: hidden;
}

.progress {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.progress.blue { background-color: #409EFF; }
.progress.orange { background-color: #F6BD16; }
.progress.purple { background-color: #E8684A; }
.progress.green { background-color: #6DC8EC; }

.progress.red { background-color: #EE6666; }
.progress.teal { background-color: #73C0DE; }
.progress.forest { background-color: #3BA272; }
.progress.salmon { background-color: #FC8452; }
.progress.purple-dark { background-color: #9A60B4; }
.progress.navy { background-color: #5470C6; }
.progress.lime { background-color: #91CC75; }
.progress.yellow { background-color: #FAC858; }
.progress.pink { background-color: #EA7CCC; }

.data-value {
  width: 60px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}

/* 入量自定义颜色 */
.dot.custom-color-0 { background-color: #FF6B6B; }
.dot.custom-color-1 { background-color: #4ECDC4; }
.dot.custom-color-2 { background-color: #45B7D1; }
.dot.custom-color-3 { background-color: #FFA624; }
.dot.custom-color-4 { background-color: #A66CFF; }
.dot.custom-color-5 { background-color: #1A936F; }
.dot.custom-color-6 { background-color: #C9A227; }
.dot.custom-color-7 { background-color: #FF8066; }
.dot.custom-color-8 { background-color: #3A86FF; }
.dot.custom-color-9 { background-color: #8BC34A; }
.dot.custom-color-10 { background-color: #F94892; }
.dot.custom-color-11 { background-color: #6A4C93; }

.progress.custom-color-0 { background-color: #FF6B6B; }
.progress.custom-color-1 { background-color: #4ECDC4; }
.progress.custom-color-2 { background-color: #45B7D1; }
.progress.custom-color-3 { background-color: #FFA624; }
.progress.custom-color-4 { background-color: #A66CFF; }
.progress.custom-color-5 { background-color: #1A936F; }
.progress.custom-color-6 { background-color: #C9A227; }
.progress.custom-color-7 { background-color: #FF8066; }
.progress.custom-color-8 { background-color: #3A86FF; }
.progress.custom-color-9 { background-color: #8BC34A; }
.progress.custom-color-10 { background-color: #F94892; }
.progress.custom-color-11 { background-color: #6A4C93; }

/* 出量自定义颜色 */
.dot.custom-color-out-0 { background-color: #FF5733; }
.dot.custom-color-out-1 { background-color: #5DADE2; }
.dot.custom-color-out-2 { background-color: #F4D03F; }
.dot.custom-color-out-3 { background-color: #58D68D; }
.dot.custom-color-out-4 { background-color: #AF7AC5; }
.dot.custom-color-out-5 { background-color: #EC7063; }
.dot.custom-color-out-6 { background-color: #3498DB; }
.dot.custom-color-out-7 { background-color: #F39C12; }
.dot.custom-color-out-8 { background-color: #2ECC71; }
.dot.custom-color-out-9 { background-color: #E74C3C; }
.dot.custom-color-out-10 { background-color: #9B59B6; }
.dot.custom-color-out-11 { background-color: #1ABC9C; }

.progress.custom-color-out-0 { background-color: #FF5733; }
.progress.custom-color-out-1 { background-color: #5DADE2; }
.progress.custom-color-out-2 { background-color: #F4D03F; }
.progress.custom-color-out-3 { background-color: #58D68D; }
.progress.custom-color-out-4 { background-color: #AF7AC5; }
.progress.custom-color-out-5 { background-color: #EC7063; }
.progress.custom-color-out-6 { background-color: #3498DB; }
.progress.custom-color-out-7 { background-color: #F39C12; }
.progress.custom-color-out-8 { background-color: #2ECC71; }
.progress.custom-color-out-9 { background-color: #E74C3C; }
.progress.custom-color-out-10 { background-color: #9B59B6; }
.progress.custom-color-out-11 { background-color: #1ABC9C; }
</style>
